﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using SharedGenomics.Core;
using SharedGenomics.Workbench.Core;
using SharedGenomics.Workbench.Views;

namespace SharedGenomics.Workbench.Presenters
{
    public class FileBrowserPresenter : Presenter, IFileBrowserPresenter
    {
        public FileBrowserPresenter(IFileBrowserView view, IOpenFileDialogView dialog)
            : base(view)
        {
            this.BrowserView = view;
            this.OpenFileDialog = dialog;

            this.BrowserView.BrowseClicked += new EventHandler(this.View_BrowseClicked);
            this.BrowserView.OpenClicked += new EventHandler(this.View_OpenClicked);
            this.BrowserView.FilePathTextChanged += new EventHandler(View_FilePathTextChanged);

            //open button should be initially disabled since no file is specified
            this.BrowserView.IsOpenEnabled = false;
        }

        private void View_OpenClicked(object sender, EventArgs e)
        {
            //raise FileOpened event
            this.FileOpened.Raise(this);
        }

        private void View_BrowseClicked(object sender, EventArgs e)
        {
            //show browse dialog - if a file is selected it should be displayed in the view
            string selectedFilePath = this.OpenFileDialog.Open();

            if (selectedFilePath != null)
            {
                this.BrowserView.FilePathText = selectedFilePath;
            }
        }

        private void View_FilePathTextChanged(object sender, EventArgs e)
        {
            //get the current file path text and enable the 'open' button if it points to an existing file
            bool exists = File.Exists(this.BrowserView.FilePathText);

            //set the enabled status of the open button if it has changed
            if (exists ^ this.BrowserView.IsOpenEnabled)
                this.BrowserView.IsOpenEnabled = exists;
        }

        private IFileBrowserView BrowserView { get; set; }
        private IOpenFileDialogView OpenFileDialog { get; set; }

        public string PromptText
        {
            get { return this.BrowserView.PromptText; }
            set { this.BrowserView.PromptText = value; }
        }

        public string FilePath
        {
            get { return this.BrowserView.FilePathText; }
        }

        public bool IsOpenEnabled
        {
            set { this.BrowserView.IsOpenEnabled = value; }
        }

        public event EventHandler FileOpened;

        public void SetFilters(params string[] filters)
        {
            this.OpenFileDialog.SetFilters(filters);
        }

        public string InitialDirectory
        {
            get { return this.OpenFileDialog.InitialDirectory; }
            set { this.OpenFileDialog.InitialDirectory = value; }
        }
    }
}
